package lvbu.wang.lvbuoperator.ui.paramset.ui;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qing.library.utils.FileUtils;
import com.qing.library.utils.L;
import com.qing.library.utils.StringUtil;
import com.qing.library.widget.CustomProgress;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.BleMotorInfo;
import lvbu.wang.lvbuoperator.bean.FirmwareVersion;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.error.BleErrorActivity;
import lvbu.wang.lvbuoperator.ui.paramset.presenter.BleParamSetPresenterCompl;
import lvbu.wang.lvbuoperator.ui.paramset.presenter.IBleParamSetPresenter;
import lvbu.wang.lvbuoperator.utils.FileUtil;
import lvbu.wang.lvbuoperator.utils.PrintQrCode1Proxy;
import lvbu.wang.lvbuoperator.utils.PrintQrCodeProxy;
import lvbu.wang.lvbuoperator.utils.StringHelper;
import lvbu.wang.lvbuoperator.xmode.CRC16;
import lvbu.wang.lvbuoperator.xmode.Mode;

/**
 * Created by DaiQing.Zha on 2017/2/27 0027.
 */
public class BleParamSetActivity extends BaseActivity implements View.OnClickListener, IBleParamSetView {

    private TextView mTvCurrentStatus;                 //当前状态
    private Button mBtnSetMotorStatus;               //设置状态，下一步
    private TextView mTvBluetoothAddress;          //蓝牙地址
    private TextView mTvBluetoothConnectState;   //蓝牙连接状态
    private Button mBtnBluetoothConnect;        //蓝牙连接
    private Button mBtnBluetoothSend;          //通过蓝牙获取点击数据
    private TextView mTvFirmwareVersion;     //固件版本
    private Button mBtnFirmwareVersion;    //固件升级
    private Button mBtnBLESignal;         //蓝牙信号强度
    private TextView mTvBLESignal;       //蓝牙信号强度
    private TextView mTvVoltageStrength;  //电压
    private Button mBtnVoltageStrength; //电压
    private Button mBtnGyroAngle;      //陀螺仪角度
    private Button mBtnRestart;       //复位

    private Button mBtnsysclose;       //复位

    private TextView mTvTypeName;                 //轮毂型号
    private TextView mTvCircumference;          //轮胎周长
    private TextView mTvPowerLevel;            //助力等级
    private TextView mTvOverSpeed;            //超速报警
    private TextView mTvBikeWeight;           //车重
    private TextView mTvLoadWeight;          //载重
    private TextView mTvBatteryPower;      //电池功率
    private TextView mTvMadeDate;         //出厂日期
    private TextView mTvGetMadeDate;    //获取出厂日期
    private LinearLayout mLlTypeName;                 //轮毂型号
    private LinearLayout mLlCircumference;          //轮胎周长
    private LinearLayout mLlPowerLevel;            //助力等级
    private LinearLayout mLlOverSpeed;            //超速报警
    private LinearLayout mLlBikeWeight;           //车重
    private LinearLayout mLlLoadWeight;          //载重
    private LinearLayout mLlBatteryPower;      //电池功率
    private LinearLayout mLlSetMadeDate;         //出厂日期
    private LinearLayout mLlGetMadeDate;    //获取出厂日期
    private LinearLayout mLLBikeName;       //电机名称
    private TextView mTvBikeName;           //电机名称
    private ProgressDialog mPDlgUpgrade;       //固件升级进度条对话框
    private ProgressDialog mPDlgDownload;    //下载进度条
    private ProgressDialog mPDlgAfterUpdateRestarting; //系统正在重启对话框[固件升级之后弹出来的]
    private Handler mHandler;                           //handler
    private FirmwareVersion mFirmwareVersion;        //固件版本
    private String mStatusCode = "";              //当前状态码
    private String[] mStatusArr = {"不转状态", "微转状态", "强转状态", "正常状态"};
    public static boolean isUpgradeEnd = false;    //升级是否结束
    public static boolean isReceive43 = false;    //是否收到43
    public static boolean isReceive73 = false;  //是否收到73
    public static String character = "";        //收到的字符串
    public static int downLoadFileSize;       //已经下载了的文件大小
    public static String fileName;           //文件名
    public static int fileSize;            //文件大小
    public static final int UPDATE_PROGRESS = 1000;      //更新进度
    public static final int DOWNLOAD_COMPLETE = 1001;  //下载完成
    public static final int FILE_MAX_SIZE = 1002;     //设置文件最大值
    private IBleParamSetPresenter iBleParamSetPresenter;
    private String productId, productName;   //产品id，产品名字


    private static final int ONE_PACKET_SIZE = 19;  //每小包数据大小
    private static final int ONE_TIME_SIZE = 1029;  //每 1kb 数据大小（包含 头，序号，序号补码，校验码）
    private static final int ONE_TIME_DATA_SIZE = 1024; //每 1kb 数据大小（不包含 头，序号，序号补码，校验码）
    final String XM_ACK = "06";  //认可响应
    final String XM_NAK = "15";  //不认可响应
    final String XM_CAN = "18";  //撤销传送
    final String XM_STA = "43";  //表示开始发送
    int mArrSize;   //表示升级包数据一共有多少个 kb
    int mCurrentSend;   //表示当前正在传输的数据是第几kb
    byte[][] upgradePacketWithHeadT;    //添加头和校验码的完整升级包
    boolean isSendFirst1KBData = false; //是否发送了第1kb数据


    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { // 定义广播接收器，接收蓝牙消息
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH)) {//蓝牙信号强度的广播
                int rssi = intent.getIntExtra("rssi", 0);
                mTvBLESignal.setText(rssi + "");
            }
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) {//蓝牙状态改变
                refreshUI_bluetooth();
            }
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_VALUE)) {
                String value = StringUtil.hex2String(intent.getByteArrayExtra("value"));
                L.e("main_C", "character === " + value);
                character = value;
                try {
                    String statusCode = StringHelper.subString(character, 4, 10);
                    if ("0B0133".equals(statusCode)) { //上报成功[固件升级成功并重启之后，电机会主动上报，3301表示升级成功]

                        Log.e("mainSuccess", "received 0133 1");
                        ThreadPool.getInstance().addTask(new Runnable() {
                            @Override
                            public void run() {
                                Map<String, Object> queryStrings = new HashMap<>();
                                queryStrings.put("bluetoothAddress", getBluetoothAddress(BleParamSetActivity.this));
                                queryStrings.put("hardwareVersion", App.getInstance().getBleMotorInfo().getHardwareVersion());
                                queryStrings.put("firmwareVersion", App.getInstance().getBleMotorInfo().getFirmwareVersion());
                                String source = IotHttpHelp.getData(RouteConstant.API_MOTOR_BLE_SET_MOTOR_INFO_LOAD_WEIGHT_UPDATE, queryStrings, true, BleParamSetActivity.this);
                                if ("success".equals(source.replace("\"", ""))) {
                                } else {
                                    showToastMsg(source);
                                }
                            }
                        });
                        if (mPDlgUpgrade.isShowing()) {   //表示升级成功
                            Log.e("mainSuccess", "received 0133 2" + fileName);
                            isUpgradeEnd = true;
                            mPDlgUpgrade.dismiss();
                            mPDlgAfterUpdateRestarting.setMessage(getString(R.string.xml_paramSet_restartSuccessDlgMsg));
                            mPDlgAfterUpdateRestarting.show();
                            if (fileName != null && !"".equals(fileName)) {  //表示升级成功
                                String firmwareVersion = fileName.substring(22, 32);
                                BleMotorInfo motorInfo = App.getInstance().getBleMotorInfo();
                                motorInfo.setFirmwareVersion(firmwareVersion);  //更新本地的电机信息
                                Log.e("mainSuccess", "received 0133 3 " + firmwareVersion);
                                mTvFirmwareVersion.setText(firmwareVersion);
                                mBtnFirmwareVersion.setVisibility(View.GONE);
                            }
                        } else if (mPDlgAfterUpdateRestarting.isShowing()) {   //固件升级之后的恢复出厂设置
                            mPDlgAfterUpdateRestarting.dismiss();
                        }
                    }
                } catch (Exception e) {
                }
                if ("73".equals(character)) {
                    isReceive73 = true;
                }
                switch (character) {
                    case XM_ACK:

                        mCurrentSend++;
                        L.e("mainTimeT", "开始发送第 " + mCurrentSend + " kb数据" + "mCurrentSend = " + mCurrentSend + " mArrSize = " + mArrSize);
                        if (mCurrentSend == (mArrSize)) {
                            BluetoothLEService.sendDataByBluetooth(new byte[]{Mode.EOT});
                            L.e("mainTimeT", "发送结束通知");
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isUpgradeEnd) {
                                        isUpgradeEnd = true;
                                        mPDlgUpgrade.dismiss();
                                        Log.e("mainSuccess", "shibai------------");
                                        mPDlgAfterUpdateRestarting.setMessage(getString(R.string.xml_paramSet_restartFailDlgMsg));
                                        mPDlgAfterUpdateRestarting.show();
                                    }
                                }
                            }, 10 * 1000);   //发送完成以后，10秒钟以内还没收到3301则表示失败

                        } else if (mCurrentSend > (mArrSize)) {
                            L.e("mainTimeT", "---升级成功---");
                        } else {
                            send1KBDataNew(upgradePacketWithHeadT[mCurrentSend]);
                        }

                        break;
                    case XM_NAK:
                        send1KBDataNew(upgradePacketWithHeadT[mCurrentSend]);
                        break;
                    case XM_CAN:
                        isUpgradeEnd = true;
                        mPDlgUpgrade.dismiss();
                        mPDlgAfterUpdateRestarting.setMessage(getString(R.string.xml_paramSet_restartFailDlgMsg));
                        mPDlgAfterUpdateRestarting.show();
                        break;
                    case XM_STA:
                        File sdCardDir = new File(FileUtils.getSDCacheDir(BleParamSetActivity.this));
                        byte[] oriUpgradePacket = FileUtil.getFileToByte(sdCardDir, fileName);    //完整的升级包文件
                        mArrSize = oriUpgradePacket.length % ONE_TIME_DATA_SIZE == 0 ? oriUpgradePacket.length / ONE_TIME_DATA_SIZE : oriUpgradePacket.length / ONE_TIME_DATA_SIZE + 1;

                        refreshUI_beginUpgrade(mArrSize * 1024);

                        byte[] newUpgradePacket = new byte[mArrSize * ONE_TIME_DATA_SIZE];
                        System.arraycopy(oriUpgradePacket, 0, newUpgradePacket, 0, oriUpgradePacket.length);
                        for (int j = newUpgradePacket.length - 1; j >= oriUpgradePacket.length; j--) {
                            newUpgradePacket[j] = Mode.EOF;
                        }
                        upgradePacketWithHeadT = new byte[mArrSize][ONE_TIME_SIZE];
                        for (int i = 0; i < mArrSize; i++) {
                            upgradePacketWithHeadT[i][0] = Mode.STX;
                            upgradePacketWithHeadT[i][1] = (byte) (i + 1);
                            upgradePacketWithHeadT[i][2] = (byte) ~(i + 1);

                            System.arraycopy(newUpgradePacket, i * ONE_TIME_DATA_SIZE, upgradePacketWithHeadT[i], 3, ONE_TIME_DATA_SIZE);

                            byte[] checkCode = new byte[2]; //crc校验码
                            CRC16 crc16 = new CRC16();
                            long longCheckCode = crc16.calcCRC(subBytes(newUpgradePacket, i * ONE_TIME_DATA_SIZE, ONE_TIME_DATA_SIZE));
                            for (int j = 0; j < crc16.getCRCLength(); j++) {
                                checkCode[crc16.getCRCLength() - j - 1] = (byte) ((longCheckCode >> (8 * j)) & 0xFF);
                            }
                            upgradePacketWithHeadT[i][ONE_TIME_SIZE - 2] = checkCode[0];
                            upgradePacketWithHeadT[i][ONE_TIME_SIZE - 1] = checkCode[1];
                            if (!isSendFirst1KBData) {
                                mCurrentSend = 0;
                                isSendFirst1KBData = true;
                                L.e("mainTimeT", "开始发送第 " + mCurrentSend + " kb数据");
                                send1KBDataNew(upgradePacketWithHeadT[mCurrentSend]);
                            }
                        }
                        break;
                }
            }
        }
    };

    /**
     * 发送1kb数据
     *
     * @param value
     */
    private void send1KBDataNew(final byte[] value) {
        int arrSize = value.length % ONE_PACKET_SIZE == 0 ? value.length / ONE_PACKET_SIZE : value.length / ONE_PACKET_SIZE + 1;
        int lastPacketSize = value.length % ONE_PACKET_SIZE;
        byte[][] data = new byte[arrSize][ONE_PACKET_SIZE];
        byte[] dataLast = new byte[lastPacketSize]; // 最后一包数据
        for (int i = 0; i < arrSize - 1; i++) {
            System.arraycopy(value, i * ONE_PACKET_SIZE, data[i], 0, ONE_PACKET_SIZE);
            BluetoothLEService.sendDataByBluetooth(data[i]);
            refreshUI_upgradeProgress((mCurrentSend * 1024) + (i * 19));
            sleep(11);
        }
        System.arraycopy(value, value.length - lastPacketSize, dataLast, 0, lastPacketSize);
        BluetoothLEService.sendDataByBluetooth(dataLast);
        refreshUI_upgradeProgress((mCurrentSend + 1) * 1024);
    }

    /**
     * 数组拷贝
     *
     * @param src
     * @param begin
     * @param count
     * @return
     */
    private byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_paramset);
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        if (bundle != null) {
            mStatusCode = bundle.getString("statusCode");
        }
        productId = getBluetoothProductId(this);
        productName = getBluetoothProductName(this);
        getSupportActionBar().setTitle("参数设置 - " + productName);

        mTvCurrentStatus = findView(R.id.tv_currentStatus);
        mTvBluetoothAddress = findView(R.id.tv_bluetoothAddress);
        mTvBluetoothConnectState = findView(R.id.tv_bluetoothConnectState);
        mTvFirmwareVersion = findView(R.id.tv_firmwareVersion);
        mTvBLESignal = findView(R.id.tv_BLESignal);
        mTvVoltageStrength = findView(R.id.tv_voltageStrength);
        mTvTypeName = findView(R.id.tv_typeName);
        mTvCircumference = findView(R.id.tv_circumference);
        mTvPowerLevel = findView(R.id.tv_powerLevel);
        mTvOverSpeed = findView(R.id.tv_overSpeed);
        mTvBikeWeight = findView(R.id.tv_bikeWeight);
        mTvLoadWeight = findView(R.id.tv_loadWeight);
        mTvBatteryPower = findView(R.id.tv_batteryPower);
        mTvMadeDate = findView(R.id.tv_madeDate);
        mTvGetMadeDate = findView(R.id.tv_getMadeDate);
        mLlTypeName = findView(R.id.ll_typeName);
        mLlCircumference = findView(R.id.ll_circumference);
        mLlPowerLevel = findView(R.id.ll_powerLevel);
        mLlOverSpeed = findView(R.id.ll_overSpeed);
        mLlBikeWeight = findView(R.id.ll_bikeWeight);
        mLlLoadWeight = findView(R.id.ll_loadWeight);
        mLlBatteryPower = findView(R.id.ll_batteryPower);
        mLlSetMadeDate = findView(R.id.ll_setMadeDate);
        mLlGetMadeDate = findView(R.id.ll_getMadeDate);
        mBtnBluetoothConnect = findView(R.id.btn_bluetoothConnect);
        mBtnBluetoothSend = findView(R.id.btn_bluetoothSend);
        mBtnFirmwareVersion = findView(R.id.btn_firmwareVersion);
        mBtnVoltageStrength = findView(R.id.btn_voltageStrength);
        mBtnGyroAngle = findView(R.id.btn_gyroAngle);
        mBtnRestart = findView(R.id.btn_restart);

        mBtnsysclose = findView(R.id.btn_sysclose);

        mBtnSetMotorStatus = findView(R.id.btn_setMotorStatus);
        mBtnBLESignal = findView(R.id.btn_BLESignal);
        //修改电机名称
        mLLBikeName = findView(R.id.ll_bikeName);
        mTvBikeName = findView(R.id.tv_bikeName);
        mLLBikeName.setOnClickListener(this);

        mBtnBluetoothConnect.setOnClickListener(this);
        mBtnBluetoothSend.setOnClickListener(this);
        mBtnFirmwareVersion.setOnClickListener(this);
        mBtnVoltageStrength.setOnClickListener(this);
        mBtnBLESignal.setOnClickListener(this);
        mBtnSetMotorStatus.setOnClickListener(this);
        mBtnGyroAngle.setOnClickListener(this);
        mBtnRestart.setOnClickListener(this);

        mBtnsysclose.setOnClickListener(this);

        mLlTypeName.setOnClickListener(this);
        mLlCircumference.setOnClickListener(this);
        mLlPowerLevel.setOnClickListener(this);
        mLlOverSpeed.setOnClickListener(this);
        mLlBikeWeight.setOnClickListener(this);
        mLlLoadWeight.setOnClickListener(this);
        mLlBatteryPower.setOnClickListener(this);
        mLlSetMadeDate.setOnClickListener(this);
        mLlGetMadeDate.setOnClickListener(this);

        mLlGetMadeDate.postDelayed(this::lazyInit, 200);


        findViewById(R.id.btn_print).setOnClickListener(view -> {
            new PrintQrCodeProxy(this).print(mTvBluetoothAddress.getText().toString().replace(":", " ").trim());
        });
        printProxy1 = new PrintQrCode1Proxy(this);
        findViewById(R.id.btn_print1).setOnClickListener(view -> {
            printProxy1.print(mTvBluetoothAddress.getText().toString().replace(":", " ").trim());
        });
    }

    private PrintQrCode1Proxy printProxy1;

    private void lazyInit() {
        mPDlgDownload = new ProgressDialog(BleParamSetActivity.this);
        mPDlgDownload.setIcon(R.mipmap.icon_notice);
        mPDlgDownload.setTitle(getString(R.string.xml_paramSet_dialogDownloadTitle));
        mPDlgDownload.setMessage(getString(R.string.xml_paramSet_dialogDownloadMsg));
        mPDlgDownload.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mPDlgDownload.setCancelable(false);

        mPDlgUpgrade = new ProgressDialog(BleParamSetActivity.this);
        mPDlgUpgrade.setIcon(R.mipmap.icon_warm);
        mPDlgUpgrade.setTitle(getString(R.string.xml_paramSet_upgradeDlgTitle));
        mPDlgUpgrade.setMessage(getString(R.string.xml_paramSet_upgradeDlgMsg));
        mPDlgUpgrade.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  //设置进度条对话框//样式（水平，旋转）
        mPDlgUpgrade.setCancelable(false);

        mPDlgAfterUpdateRestarting = new ProgressDialog(BleParamSetActivity.this);
        mPDlgAfterUpdateRestarting.setIcon(R.mipmap.icon_notice);
        mPDlgAfterUpdateRestarting.setTitle(getString(R.string.xml_paramSet_restartDlgTitle));
        mPDlgAfterUpdateRestarting.setProgressStyle(ProgressDialog.STYLE_SPINNER);   //设置进度条对话框//样式（水平，旋转）
        mPDlgAfterUpdateRestarting.setCancelable(false);
        mPDlgAfterUpdateRestarting.setButton(getString(R.string.xml_comm_confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mPDlgAfterUpdateRestarting.dismiss();
            }
        });
        registerBroadcast();
        initData();
        refreshUI_bluetooth();
    }

    /**
     * //     * 初始化数据
     */
    private void initData() {
        mHandler = new Handler();
        iBleParamSetPresenter = new BleParamSetPresenterCompl(this);
        refreshUI_motorInfo();
//        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { // 已连接，断开连接
//            BluetoothLEService.disConnect();  // 断开车辆蓝牙
//        }
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { // 未连接，开始连接
            BluetoothLEService.connect(); // 连接车辆蓝牙
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_setMotorStatus:
                iBleParamSetPresenter.clickSetMotorStatus(this);
                break;
            case R.id.btn_bluetoothConnect:
                iBleParamSetPresenter.clickConnectBluetooth(this);
                break;
            case R.id.btn_bluetoothSend:
                iBleParamSetPresenter.clickGetDataByBluetooth();
                break;
            case R.id.btn_BLESignal:
                iBleParamSetPresenter.clickBleSignalStrength(this);
                break;
            case R.id.btn_voltageStrength:
                iBleParamSetPresenter.clickGetVoltage(this);
                break;
            case R.id.btn_gyroAngle:
                iBleParamSetPresenter.clickAdjustGyroAngle();
                break;
            case R.id.btn_restart:
                iBleParamSetPresenter.clickRestart(this);
                break;
            case R.id.btn_sysclose:
                iBleParamSetPresenter.clickSysclose(this);
                break;
            case R.id.ll_typeName:
                iBleParamSetPresenter.clickSelectTypeName(this, productId);
                break;
            case R.id.ll_circumference:
                iBleParamSetPresenter.clickSelectCircumference(this);
                break;
            case R.id.ll_powerLevel:
                iBleParamSetPresenter.clickAdjustPowerLevel(this);
                break;
            case R.id.ll_overSpeed:
                iBleParamSetPresenter.clickOverSpeedAlarm(this);
                break;
            case R.id.ll_bikeWeight:
                iBleParamSetPresenter.clickBikeWeight(this);
                break;
            case R.id.ll_loadWeight:
                iBleParamSetPresenter.clickLoadWeight(this);
                break;
            case R.id.ll_batteryPower:
                iBleParamSetPresenter.clickBatteryPowerAndBatteryModel(this, productId);
                break;
            case R.id.ll_setMadeDate:
                iBleParamSetPresenter.clickSetMadeDate();
                break;
            case R.id.ll_getMadeDate:
                iBleParamSetPresenter.clickGetMadeData();
                break;
            case R.id.btn_firmwareVersion:
                iBleParamSetPresenter.clickUpdateFirmware(this, mFirmwareVersion);
                break;
            case R.id.ll_bikeName:
                iBleParamSetPresenter.clickModifyName(this);
                break;
        }
    }

    /**
     * 将状态码转换为状态
     *
     * @param mStatusCode
     * @return
     */
    private String getStatusNameByCode(String mStatusCode) {
        String statusName = "";
        if ("01".equals(mStatusCode)) {
            statusName = mStatusArr[0];
        }
        if ("02".equals(mStatusCode)) {
            statusName = mStatusArr[1];
        }
        if ("03".equals(mStatusCode)) {
            statusName = mStatusArr[2];
        }
        if ("FF".equalsIgnoreCase(mStatusCode)) {
            statusName = mStatusArr[3];
        }
        return statusName;
    }

    /**
     * 注册广播接收器
     */
    private void registerBroadcast() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH);
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_VALUE);
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    public void showProcess(final int type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomProgress.show(BleParamSetActivity.this, getProgressTipString(type), false, null);
            }
        });
    }

    @Override
    public void hideProcess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomProgress.dissMiss();
            }
        });
    }

    @Override
    public void showToast(int type) {
        showToastMsg(getToastString(type));
    }

    @Override
    public void showToast(String toast) {
        showToastMsg(toast);
    }

    @Override
    public void showToast(int type, String toast) {
        showToastMsg(getToastString(type) + toast);
    }

    private static final String TAG = "BleParamSetActivity";

    @Override
    public void refreshUI_motorInfo() {
        runOnUiThread(() -> {
            BleMotorInfo motorInfo = App.getInstance().getBleMotorInfo();
            mStatusCode = motorInfo.getStatusCode();
            mTvBluetoothAddress.setText(motorInfo.getBluetoothAddress());
            mTvTypeName.setText(motorInfo.getMotorSeries());
            mTvCircumference.setText(motorInfo.getCircumference() + "");
            mTvFirmwareVersion.setText(motorInfo.getFirmwareVersion());
            mTvPowerLevel.setText(motorInfo.getPowerLevel() + "");
            mTvOverSpeed.setText(motorInfo.getSpeedLimitValue() + "");
            mTvBikeWeight.setText(motorInfo.getBikeWeight() + "");
            mTvLoadWeight.setText(motorInfo.getLoadWeight() + "");
            Log.e(TAG, "run: " + motorInfo.getMotorName(), null);
            mTvBikeName.setText(motorInfo.getMotorName() + "");
            String statusName = getStatusNameByCode(mStatusCode);
            mTvCurrentStatus.setText(statusName);
            mTvBatteryPower.setText(motorInfo.getBatteryRate() + "");
            iBleParamSetPresenter.clickGetMadeData();
        });
    }

    @Override
    public void refreshUI_bluetooth() {
        runOnUiThread(() -> {
            if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_SCAN
                    || getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTING) { //正在扫描或者
                mTvBluetoothConnectState.setText("蓝牙连接中···");
            }
            if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { //连接成功
                mBtnBluetoothSend.setVisibility(View.VISIBLE);
                mBtnBluetoothConnect.setVisibility(View.GONE);
                mTvBluetoothConnectState.setText("[蓝牙已连接]");
                iBleParamSetPresenter.checkIsHaveNewFirmware(BleParamSetActivity.this);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                iBleParamSetPresenter.clickGetDataByBluetooth();
            }
            if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { //未连接
                mBtnBluetoothSend.setVisibility(View.GONE);
                mBtnBluetoothConnect.setVisibility(View.VISIBLE);
                mTvBluetoothConnectState.setText("[蓝牙未连接]");
            }
        });
    }

    @Override
    public void refreshUI_motorStatus(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvCurrentStatus.setText(status);
            }
        });
    }

    @Override
    public void refreshUI_voltage(final String voltage) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvVoltageStrength.setText(voltage);
            }
        });
    }

    @Override
    public void refreshUI_powerLevel(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvPowerLevel.setText(value);
            }
        });
    }

    @Override
    public void refreshUI_overSpeed(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvOverSpeed.setText(value);
            }
        });
    }

    @Override
    public void refreshUI_bikeWeight(final String bikeWeight) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvBikeWeight.setText(bikeWeight);
            }
        });
    }

    @Override
    public void refreshUI_loadWeight(final String loadWeight) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvLoadWeight.setText(loadWeight);
            }
        });
    }

    @Override
    public void refreshUI_typeName(final String type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvTypeName.setText(type);
            }
        });
    }

    @Override
    public void refreshUI_circumference(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvCircumference.setText(value);
            }
        });
    }

    @Override
    public void refreshUI_downLoadProgress(final int type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (type) {
                    case FILE_MAX_SIZE:
                        mPDlgDownload.setMax(fileSize);
                        mPDlgDownload.show();
                        break;
                    case UPDATE_PROGRESS:
                        mPDlgDownload.setProgress(downLoadFileSize);
                        break;
                    case DOWNLOAD_COMPLETE:
                        mPDlgDownload.dismiss();
                        iBleParamSetPresenter.checkIsCanUpdate(BleParamSetActivity.this);
                        break;
                }
            }
        });
    }

    @Override
    public void refreshUI_afterReceive06() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!BleParamSetActivity.isUpgradeEnd) {
                            isUpgradeEnd = true;
                            mPDlgUpgrade.dismiss();
                            mPDlgAfterUpdateRestarting.setMessage(getString(R.string.xml_paramSet_restartFailDlgMsg));
                            mPDlgAfterUpdateRestarting.show();
                        }
                    }
                }, 10 * 1000);
            }
        });
    }

    @Override
    public void refreshUI_upgradeProgress(final int progress) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPDlgUpgrade.setProgress(progress);
            }
        });
    }

    @Override
    public void refreshUI_dismissDownload() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPDlgDownload.dismiss();
            }
        });
    }

    @Override
    public void refreshUI_beginUpgrade(final int finalArrSize) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPDlgUpgrade.setMax(finalArrSize);//进度最大值
                mPDlgUpgrade.setProgress(0);    //进度初始值
                mPDlgUpgrade.show();           //显示进度条
            }
        });
    }

    @Override
    public void refreshUI_checkFirmware(final FirmwareVersion firmwareVersion) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mFirmwareVersion = firmwareVersion;
                if (firmwareVersion != null && !"".equals(firmwareVersion.getFirmwareVersion())) {
                    mBtnFirmwareVersion.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void refreshUI_madeDate(final String date) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvMadeDate.setText(date);
            }
        });
    }

    @Override
    public void refreshUI_getMadeDate(final String date) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if ("000000".equals(date)) {
                    mTvGetMadeDate.setText("尚未设置，请点击设置");
                    mTvMadeDate.setText("尚未设置，请点击设置");
                } else {
                    mTvGetMadeDate.setText(date);
                    mTvMadeDate.setText(date);
                }
            }
        });
    }

    @Override
    public void refreshUI_batteryPowerAndMode(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvBatteryPower.setText(value);
            }
        });
    }

    /**
     * 刷新电机名称
     *
     * @param bikeName
     */
    @Override
    public void refreshUI_bikeName(final String bikeName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvBikeName.setText(bikeName);
            }
        });
    }

    /**
     * 获取自定义progress的提示信息
     *
     * @param type
     * @return
     */
    private String getProgressTipString(int type) {
        String string = "";
        if (type == PROGRESS_TYPE_NAME) string = getString(R.string.xml_paramSet_alterTypeName);
        if (type == PROGRESS_CIRCUMFERENCE)
            string = getString(R.string.xml_paramSet_alterCircumference);
        if (type == PROGRESS_CHANGE_STATUS_CHANGES_ING)
            string = getString(R.string.xml_paramSet_changeStatusF_changeIng);
        if (type == PROGRESS_ADJUST_POWER_LEVEL_ING)
            string = getString(R.string.xml_paramSet_adjustPowerLevelIng);   //正在调节助力等级
        if (type == PROGRESS_ADJUST_BIKE_WEIGHT)
            string = getString(R.string.xml_paramSet_adjustBikeWeight);   //修改车重
        if (type == PROGRESS_ADJUST_LOAD_WEIGHT)
            string = getString(R.string.xml_paramSet_adjustLoadWeight);   //修改载重
        return string;
    }

    /**
     * 获取toast信息
     *
     * @param type
     * @return
     */
    private String getToastString(int type) {
        String string = "";
        if (type == TOAST_COMM_BLE_NOT_SUPPORT)
            string = getString(R.string.toast_comm_bleNotSupport);           //手机不支持低功耗蓝牙
        if (type == TOAST_COMM_BLUETOOTH_NOT_OPEN)
            string = getString(R.string.toast_comm_bluetoothNotOpen);  //手机蓝牙尚未打开
        if (type == TOAST_COMM_BLE_CONNECTING)
            string = getString(R.string.toast_comm_bleConnecting);         //蓝牙连接中
        if (type == TOAST_COMM_BLE_IS_NOT_CONNECT)
            string = getString(R.string.toast_comm_bleIsNotConnect);         //蓝牙尚未连接
        if (type == TOAST_PARAM_SET_RESET_SUCCESS)
            string = getString(R.string.toast_paramSet_resetSuccess);    //重启操作成功
        if (type == TOAST_PARAM_SET_CLOSED_SUCCESS)
            string = getString(R.string.toast_paramSet_closeSuccess);    //关机操作成功
        if (type == TOAST_PARAM_SET_RESET_FAIL)
            string = getString(R.string.toast_paramSet_resetFail);    //重启操作失败
        if (type == TOAST_UPGRADE_SUCCESS_NOT_STATIC)
            string = getString(R.string.toast_paramSet_upgradeSuccessNotStatic);    //重启操作失败
        if (type == TOAST_UPGRADE_SUCCESS_UNDER_VOLTAGE)
            string = getString(R.string.toast_paramSet_upgradeSuccessUnderVoltage);    //重启操作失败
        return string;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothLEService.disConnect();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_paramset, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_seeError) {

            Intent intent = new Intent(BleParamSetActivity.this, BleErrorActivity.class);
            startActivity(new Intent(intent));
        }
        return super.onOptionsItemSelected(item);
    }
}
